'use client';

import { Modal, Form, InputNumber, Input, message } from 'antd';
import { useState } from 'react';
import { ModifyOrderAmountForm } from '@/types/order';

interface ModifyOrderAmountModalProps {
  onCancel?: () => void;
  onSuccess?: () => void;
  onSubmit?: (newAmount: number, remark: string) => Promise<void>;
  onClose?: () => void;
  orderInfo?: {
    id: string;
    orderNumber: string;
    orderAmount: number;
  };
  orderId?: string;
  orderNumber?: string;
  currentAmount?: number;
}

const ModifyOrderAmountModal: React.FC<ModifyOrderAmountModalProps> = ({
  onCancel,
  onSuccess,
  onSubmit,
  onClose,
  orderInfo,
  orderId,
  orderNumber,
  currentAmount,
}) => {
  const [form] = Form.useForm<ModifyOrderAmountForm>();
  const [loading, setLoading] = useState(false);

  // 获取订单信息
  const order = orderInfo || { 
    id: orderId || '', 
    orderNumber: orderNumber || '', 
    orderAmount: currentAmount || 0 
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      if (onSubmit) {
        await onSubmit(values.newAmount, values.remark || '');
      } else {
        // TODO: 调用API修改订单金额
        console.log('修改订单金额:', { ...values, orderId: order.id });
        message.success('订单金额修改成功');
      }
      
      form.resetFields();
      onSuccess?.();
      onClose?.();
    } catch (error) {
      console.error('修改订单金额失败:', error);
      message.error('修改订单金额失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    form.resetFields();
    onCancel?.();
    onClose?.();
  };

  return (
    <Modal
      title="修改订单金额"
      open={true}
      onOk={handleSubmit}
      onCancel={handleCancel}
      confirmLoading={loading}
      width={500}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          orderId: order.id,
          newAmount: order.orderAmount,
        }}
      >
        <Form.Item label="订单信息">
          <div className="p-3 bg-gray-50 rounded">
            <div>订单编号: {order.orderNumber}</div>
            <div>当前金额: ¥{order.orderAmount.toFixed(2)}</div>
          </div>
        </Form.Item>

        <Form.Item
          name="newAmount"
          label="新金额"
          rules={[
            { required: true, message: '请输入新金额' },
            { type: 'number', min: 0, message: '金额不能为负数' },
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            placeholder="请输入新金额"
            precision={2}
            min={0}
            addonBefore="¥"
          />
        </Form.Item>

        <Form.Item
          name="remark"
          label="修改原因"
          rules={[
            { required: true, message: '请输入修改原因' },
          ]}
        >
          <Input.TextArea
            placeholder="请输入修改原因"
            rows={3}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ModifyOrderAmountModal; 